<template>
	<a-drawer
		class="label_edit_drawer"
		title="编辑标签"
		:width="720"
		:visible="showStatus"
		:ok-loading="loading"
		unmount-on-close
		@ok="confirm"
		@cancel="cancel"
	>
		<div class="drawer_content">
			<div class="content_wrap">
				<div class="title">
					<a-typography-text bold>系统标签库</a-typography-text>
					<a-input-search
						v-model="searchKey"
						:style="{ width: '185px' }"
						placeholder="搜索标签"
						allow-clear
						@clear="resetSearchList"
						@search="searchLabelList"
					/>
				</div>
				<div v-if="Array.isArray(searchList) && searchList.length" class="classify_label_list">
					<div class="classify">
						<div class="classify_list_wrap">
							<div
								v-for="(label, index) in searchList"
								:key="`label${index}`"
								class="label_item"
								:class="{ active: selectLabelList.find((e) => e.id === label.id) }"
								@click="selectLabel(label)"
							>
								<a-typography-text class="label_text" :ellipsis="{ showTooltip: true }">
									{{ label.labelName }}
								</a-typography-text>
							</div>
						</div>
					</div>
				</div>
				<div v-else class="classify_label_list">
					<div
						v-for="(classify, classifyIndex) in classifyLabelList"
						:key="`classify${classifyIndex}`"
						class="classify"
					>
						<div class="classify_title">
							<div class="title_text">{{ classify.labelName }}</div>
							<a-input
								v-if="classify.id === 3"
								v-model="labelName"
								:style="{ width: '185px' }"
								placeholder="添加自定义标签"
								:max-length="10"
								allow-clear
								@press-enter="addLabel"
							>
								<template #suffix>
									<icon-plus class="add_label_btn" @click="addLabel" />
								</template>
							</a-input>
						</div>
						<div class="classify_list_wrap">
							<div
								v-for="(label, index) in classify.labelList"
								:key="`label${index}`"
								class="label_item"
								:class="{ active: selectLabelList.find((e) => e.id === label.id) }"
								@click="selectLabel(label)"
							>
								<a-typography-text class="label_text" :ellipsis="{ showTooltip: true }">
									{{ label.labelName }}
								</a-typography-text>
								<a-popconfirm
									content="删除后可再添加"
									content-class="label_del_confirm_popup"
									ok-text="删除"
									:ok-button-props="{ status: 'danger' }"
									@ok="deleteLabel(label.id)"
								>
									<icon-close-circle-fill v-if="classify.id === 3" class="del_btn" @click.stop />
								</a-popconfirm>
							</div>
						</div>
					</div>
				</div>
			</div>
			<div class="content_wrap">
				<div class="title">
					<a-typography-text bold>活动标签</a-typography-text>
				</div>
				<div class="activity_label_wrap">
					<div
						v-for="(label, index) in selectLabelList"
						:key="`activityLabel${index}`"
						class="activity_label_item"
					>
						<div class="label_text">{{ label.labelName }}</div>
						<icon-close class="cancel_label_btn" @click="cancelLabel(label)" />
					</div>
				</div>
			</div>
		</div>
	</a-drawer>
</template>
<script setup lang="ts">
import { ref, computed } from 'vue';
import { label, activity, errors } from '@/api';
import { Message } from '@arco-design/web-vue';
interface labelItem {
	createTime: number | string;
	createUser: number;
	id: number;
	labelName: string;
	labelParent: number;
	labelType: number;
	labelList?: Array<labelItem>;
}
const labelList = ref<Array<labelItem>>([]);
const classifyLabelList = computed(() => {
	// 这里对获取的列表做数据调整
	let list: Array<labelItem> = [];
	if (!Array.isArray(labelList.value) || !labelList.value.length) {
		return [];
	}
	labelList.value.forEach((e) => {
		// 说明是首位的
		if (!e.labelParent) {
			let info = e;
			info.labelList = [];
			list.push(info);
		} else {
			// 说明实在前方id的子集
			let info = list.find((k) => k.id === e.labelParent);
			if (info) {
				let labelList = info.labelList ? [...info.labelList] : [];
				labelList.push(e);
				info.labelList = labelList;
			}
		}
	});
	return list;
});
const getLabelList = async () => {
	try {
		const { data, ok } = await label.getLabelList();
		if (!ok) {
			return;
		}
		labelList.value = data.data || [];
	} catch (error) {
		errors(error);
	}
};
getLabelList();

const searchKey = ref('');
const searchList = ref<Array<labelItem>>([]);
const searchLabelList = async () => {
	try {
		const { data, ok } = await label.searchLabelList({ labelName: searchKey.value });
		if (!ok) {
			return;
		}
		searchList.value = data.data || [];
	} catch (error) {
		errors(error);
	}
};
const resetSearchList = async () => {
	searchList.value = [];
};

const selectLabelList = ref<Array<labelItem>>([]);
const deleteLabelList = ref<Array<labelItem>>([]);
const selectLabel = (labelInfo: labelItem) => {
	// 判断当前是否存在，如果存在，那么走取消逻辑
	if (selectLabelList.value.find((e) => e.id === labelInfo.id)) {
		cancelLabel(labelInfo);
	} else {
		// 判断删除的列表中是否存在，如果存在，删除列表去掉
		if (deleteLabelList.value.find((e) => e.id === labelInfo.id)) {
			deleteLabelList.value = selectLabelList.value.filter((e) => {
				return e.id !== labelInfo.id;
			});
		}
		selectLabelList.value.push(labelInfo);
	}
};
const cancelLabel = (labelInfo: labelItem) => {
	deleteLabelList.value.push(labelInfo);
	selectLabelList.value = selectLabelList.value.filter((e) => {
		return e.id !== labelInfo.id;
	});
};

const labelName = ref('');
let addLabelLoading = false;
const addLabel = async () => {
	if (addLabelLoading) {
		return;
	}
	addLabelLoading = true;
	if (!labelName.value || !labelName.value.trim()) {
		Message.error('请输入标签内容');
		addLabelLoading = false;
		return;
	}
	try {
		const { data, ok } = await label.addLabel({ labelName: labelName.value });
		if (!ok) {
			addLabelLoading = false;
			return;
		}
		console.log('data', data);
		getLabelList();
		Message.success(data.msg);
		addLabelLoading = false;
	} catch (error) {
		addLabelLoading = false;
		errors(error);
	}
};

const deleteLabel = async (labelId: number) => {
	try {
		const { data, ok } = await label.deleteLabel(labelId);
		if (!ok) {
			return;
		}
		Message.success(data.msg);
		getLabelList();
	} catch (error) {
		errors(error);
	}
};

const showStatus = ref(false);
const activityInfo = ref<{ id: number; label: string } | null>(null);
const initList = async () => {
	await getLabelList();
	if (activityInfo.value && activityInfo.value.label) {
		const labelIdList: Array<string> = activityInfo.value.label.split(',');
		const list: Array<labelItem> = [];
		labelIdList.forEach((e) => {
			let lableInfo = labelList.value.find((label) => label.id === Number(e));
			if (e && lableInfo) {
				list.push(lableInfo);
			}
		});
		selectLabelList.value = list;
	}
};
const show = async (info: any) => {
	if (!info) {
		return;
	}
	activityInfo.value = info;
	initList();
	showStatus.value = true;
};
const close = () => {
	deleteLabelList.value = [];
	showStatus.value = false;
};
const loading = ref(false);
interface emitsType {
	(e: 'refresh'): void;
}
const emits = defineEmits<emitsType>();
const confirm = async () => {
	if (loading.value) {
		return;
	}
	loading.value = true;
	try {
		const body = {
			activityId: (activityInfo.value && activityInfo.value.id) || 0,
			bindLabelIds: selectLabelList.value.map((e) => e.id),
			deleteLabelIds: deleteLabelList.value.map((e) => e.id),
		};
		const { data, ok } = await label.bindActivityLabel(body);
		if (!ok) {
			loading.value = false;
			return;
		}
		Message.success(data.msg);
		loading.value = false;
		emits('refresh');
		close();
	} catch (error) {
		loading.value = false;
		errors(error);
	}
};
const cancel = () => {
	close();
};
defineExpose({
	show,
	close,
});
</script>
<style lang="less">
.label_edit_drawer {
	width: 100%;
	.arco-drawer-body {
		padding: 0;
	}
	.drawer_content {
		display: flex;
		height: 100%;
		flex-flow: row nowrap;
	}
	.content_wrap {
		position: relative;
		width: 50%;
		height: 100%;
		box-sizing: border-box;
		padding: 16px;
		.title {
			width: 100%;
			height: 32px;
			display: flex;
			flex-flow: row nowrap;
			align-items: center;
			justify-content: space-between;
		}
		& + .content_wrap {
			&::before {
				content: '';
				position: absolute;
				left: 0;
				top: 0;
				width: 1px;
				height: 100%;
				background-color: rgba(234, 234, 234, 1);
			}
		}
	}
	.classify_label_list {
		margin-top: 14px;
		width: 100%;
		height: calc(100% - 48px);
		overflow-x: hidden;
		overflow-y: auto;
		.classify {
			width: 100%;
			& + .classify {
				margin-top: 16px;
			}
		}
		.add_label_btn {
			cursor: pointer;
		}
		.classify_title {
			width: 100%;
			height: 32px;
			font-size: 14px;
			color: #808080;
			line-height: 20px;
			display: flex;
			display: flex;
			flex-flow: row nowrap;
			align-items: center;
			justify-content: space-between;
		}
		.classify_list_wrap {
			margin-top: 8px;
			display: grid;
			grid-template-columns: repeat(4, 1fr);
			gap: 12px 8px;
		}
		.label_item {
			position: relative;
			width: 100%;
			min-width: 0;
			box-sizing: border-box;
			color: rgba(89, 89, 89, 1);
			border: 1px solid rgba(234, 234, 234, 1);
			cursor: pointer;
			.label_text {
				width: 100%;
				font-size: 14px;
				line-height: 20px;
				text-align: center;
				overflow: hidden;
				margin: 0;
			}
			&.active {
				color: #386cff;
				border-color: #386cff;
			}
			.del_btn {
				position: absolute;
				top: 0;
				right: 0;
				transform: translate(50%, -50%);
				font-size: 16px;
				display: block;
				cursor: pointer;
			}
		}
	}
	.activity_label_wrap {
		margin-top: 12px;
		width: 100%;
		display: flex;
		flex-flow: row wrap;
		align-items: center;
		gap: 12px 8px;
		.activity_label_item {
			padding: 2px 4px;
			display: flex;
			flex-flow: row nowrap;
			align-items: center;
			border: 1px solid rgba(234, 234, 234, 1);
		}
		.label_text {
			line-height: 20px;
			color: rgba(89, 89, 89, 1);
			font-size: 14px;
		}
		.cancel_label_btn {
			margin-left: 4px;
			cursor: pointer;
		}
	}
}
.label_del_confirm_popup {
	position: relative;
	width: 260px;
	&::before {
		content: '确认删除？';
		position: relative;
		display: block;
		width: 100%;
		color: #262626;
		font-weight: bold;
	}
	&.arco-popconfirm-popup-content {
		.arco-popconfirm-body {
			font-size: 14px;
			line-height: 20px;
			color: rgba(0, 0, 0, 0.65);
			.arco-popconfirm-icon {
				display: none;
			}
		}
	}
}
</style>
